<script setup lang="ts">
  import { ContentWrap } from '@/components/ContentWrap'
  import { Search } from '@/components/Search'
  import { Dialog } from '@/components/Dialog'
  import {ElRow, ElCol, ElSwitch} from 'element-plus'
  import { useI18n } from '@/hooks/web/useI18n'
  import { ElButton, ElTag } from 'element-plus'
  import { Table } from '@/components/Table'
  import {delTableListApi,getListApi ,getDelcoupom,getAddcoupom} from '@/api/table'
  import { useTable } from '@/views/Example/Dialog/useTable'
  import { CouponData } from '@/api/table/types'
  import { h, ref, unref, reactive } from 'vue'
  import Write from './components/Write.vue'
  import Detail from './components/Detail.vue'
  import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
  import { TableColumn } from '@/types/table'
  import {useEmitt} from "@/hooks/web/useEmitt";
  import {push} from "echarts/types/src/component/dataZoom/history";

  const { register, tableObject, methods } = useTable<CouponData>({
    getListApi: getListApi,
    delListApi: getDelcoupom,
    response: {
      list: 'list',
      total: 'total'
    },
    defaultParams: {
      title: 's'
    }
  })

  const { getList, setSearchParams } = methods

  getList()

  const { t } = useI18n()

  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'coupon_id',
      label: t('序号'),
      type: 'index'
    },
    {
      field: 'coupon_name',
      label: t('couponDemo.couponName')
    },
    {
      field: 'start_date',
      label: t('couponDemo.couponTime')
    },
    {
      field: 'end_date',
      label: t('couponDemo.couponTimes')
    },
    {
      field: 'online',
      label: t('couponDemo.shangjiao'),
      sortable: true
    },
    {
      field: 'mode',
      label: t('couponDemo.faosong'),
      formatter: (row:CouponData) => {
        return h(
                'span',
                row.mode === 2 ? t('人工发放') : (row.mode > 2 ? t('活动领取') : t('自动发放'))
        )
      }
    },
    {
      field: 'issue_quantity',
      label: t('couponDemo.faoshu')
    },
    {
      field: 'surplus',
      label: t('couponDemo.sum')
    },
    {
      field: 'action',
      label: t('tableDemo.action')
    }
  ])
  const crudFrom = reactive<CrudSchema[]>([
    {
      field: 'couponName',
      label: t('优惠券'),
      component: 'Input',
    },
    //优惠券类型
    {
      field: 'coupon_type',
      label: t('优惠券类型'),
      component: 'Radio',
      componentProps: {
        options: [
          {
            label: '满减券',
            value: '1'
          },
          {
            label: '优惠券',
            value: '2'
          }
        ]
      }
    },
    //优惠金额
    {
      field: 'coupon_price',
      label: t('优惠金额'),
      component: 'Input',
    },
    //开始时间
    {
      field: 'startDate',
      component: 'DatePicker',
      label: t('formDemo.in_time'),
      componentProps: {
        type: 'date',
        format: 'YYYY/MM/DD',
        valueFormat: 'YYYY-MM-DD',
        slots: {
          default: true
        }
      }
    },
    //结束时间
    {
      field: 'endDate',
      component: 'DatePicker',
      label: t('formDemo.in_err'),
      componentProps: {
        type: 'date',
        format: 'YYYY/MM/DD',
        valueFormat: 'YYYY-MM-DD',
        slots: {
          default: true
        }
      }
    },
    //上线/下线
    {
      field: 'online',
      label: t('formDemo.in_ty'),
      component: 'Radio',
      componentProps: {
        options: [
          {
            label: '上线',
            value: '1'
          },
          {
            label: '下线',
            value: '2'
          }
        ]
      }
    },
    //发行数量
    {
      field: 'issue_quantity',
      label: t('发行数量'),
      component: 'Input',
    },
    //获取方式
    {
      field: 'mode',
      label: t('获取方式'),
      component: 'Select',
      formItemProps: {
        //rules: [required()]
      },
      componentProps: {
        options: [
          {
            label: '自动发放',
            value: 1
          },
          {
            label: '活动领取',
            value: 2
          },
          {
            label:'人工发放',
            value:3,
          },
          {
            label:'无限制',
            value:4,
          },
        ]
      }
    },
    //优惠券类型
    {
      field: 'type',
      label: t('优惠券类型'),
      component: 'Select',
      formItemProps: {
        //rules: [required()]
      },
      componentProps: {
        options: [
          {
            label: '商品',
            value: 1
          },
          {
            label: '视频',
            value: 2
          },
          {
            label:'无限制',
            value:3,
          },
        ]
      }
    },
    //备注
    {
      field: 'remark',
      label: t('备注'),
      component: 'Input',
    }
  ])

  const { allSchemas } = useCrudSchemas(crudSchemas)

  const dialogVisible = ref(false)

  const dialogTitle = ref('')

  const AddAction = () => {
    dialogTitle.value = t('exampleDemo.add')
    tableObject.currentRow = null
    dialogVisible.value = true
    actionType.value = ''

  }


  const delLoading = ref(false)

  const delData = async (row: CouponData | null, multiple: boolean) => {
    tableObject.currentRow = row
    const { delList, getSelections } = methods
    const selections = await getSelections()
    delLoading.value = true
    await delList(
            multiple ? selections.map((v) => v.coupon_id) : [tableObject.currentRow?.coupon_id as number],
            multiple
    ).finally(() => {
      delLoading.value = false
    })
  }

  const actionType = ref('')

  const action = (row: CouponData, type: string) => {
    dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
    actionType.value = type
    tableObject.currentRow = row
    dialogVisible.value = true
  }

  const writeRef = ref<ComponentRef<typeof Write>>()

  const loading = ref(false)

  const save = async () => {
    const write = unref(writeRef)
    await write?.elFormRef?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        const data = (await write?.getFormData()) as CouponData
        const res = await getAddcoupom(data)
                .catch(() => {})
                .finally(() => {
                  loading.value = false
                  console.log(data)
                })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }
    })
  }
</script>

<template>
  <ContentWrap :title="t('tableDemo.table')" :message="t('tableDemo.tableDes')">

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
    </div>
    <Table
            v-model:pageSize="tableObject.pageSize"
            v-model:currentPage="tableObject.currentPage"
            :columns="allSchemas.tableColumns"
            :data="tableObject.tableList.slice(
            (tableObject.currentPage - 1) * tableObject.pageSize,
             tableObject.currentPage * tableObject.pageSize)"
            :loading="tableObject.loading"
            :pagination="{
        total: tableObject.total
      }"
            @register="register"
    >
      <template #action="{ row }">
        <ElButton
                type="success"
                v-hasPermi="['example:dialog:view']"
                @click="action(row, 'detail')"
        >
          {{ t('exampleDemo.detail') }}
        </ElButton>
        <ElButton type="danger" v-hasPermi="['example:dialog:delete']" @click="delData(row, false)">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
      <template #online="{row}">
        <ElSwitch
                v-model="row.online"
                class="ml-2"
                inline-prompt
                style="-el-switch-off-color: #13ce66; -el-switch-off-color: #ff4949"
                active-text="上架"
                inactive-text="下架"
                :active-value="1"
                :inactive-value="2"
        />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
            v-if="actionType !== 'detail'"
            ref="writeRef"
            :form-schema="crudFrom"
            :current-row="tableObject.currentRow"
    />

    <Detail
            v-if="actionType === 'detail'"
            :detail-schema="allSchemas.detailSchema"
            :current-row="tableObject.currentRow"
    />

        <template #footer>
          <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save">
            {{ t('exampleDemo.save') }}
          </ElButton>
          <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
        </template>
  </Dialog>
</template>
